const {getIPAddress, saveIP, ISIPAddress, countIPAddress} = require("../../utils/IP");
const {db} = require("../../config/dbconfig");
exports.IpAddress = async (req, res, next) => {
    try {
        let rawIP = req.query.ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress || '';
        let userIP = rawIP.trim();
        console.log("请求IP：", userIP);

        if (!userIP) {
            return res.cc("空", 1);
        }

        if (userIP === "127.0.0.1") {
            return res.cc("本地", 1);
        }

        const ipData = await getIPAddress(userIP);
        const count = await ISIPAddress(userIP);

        if (count > 0) {
            await countIPAddress(userIP);
            return res.cc("ok", 0);
        } else {
            await saveIP(userIP, ipData);
            return res.cc("ok", 0);
        }
    } catch (error) {
        console.error("处理IP出错:", error);
        return res.cc("服务器内部错误", 1);
    }
}
exports.getIpAddressListByCity = async (req, res,) => {
    //按时间排序
    const sql = "select * from ip_addresses order by update_time desc"
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: "ok",
            data: result
        })
    })
}
//最近访问的5条记录
exports.getRecentIpAddressList = async (req, res,) => {
    const sql = "select * from ip_addresses order by update_time desc limit 5"
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: "ok",
            data: result
        })
    })
}